$(function () {
var app = new Vue({
	el: '#app'
	,data:{
		taskId:$("#taskId").val()
		,taskName:$("#taskName").val()
		,caseDatagrid:[]
		,queryCaseData:{activeFlag:'1',page:1,rows:50,taskId:$("#taskId").val(),orderColum:"order_index"}//查询条件
		,selectedCase:[]
		,totalNum:0//分页控件配置
		,currentCase:{}
		,addCase:{moduleCode:0,moduleName:'无所属模块'}
		,dialogConfig:{
			formLabelWidth:'120px'
			,caseAddDialogVisible:false
			,taskDialogVisible:false
			,statusDialogVisible:false
			,taskGroupVisible:false
			,taskMoveGroupVisible:false
		}
		,rules:[]
		,porjectDatagird:[]
		,moduleSelectData:[]
		,typeData:[]
		,levelData:[]
		,caseStatus:[{
			name:'TODO',
			code:"0"
		},{
			name:'OK',
			code:"1"
		},{
			name:'NG',
			code:"2"
		},{
			name:'BLOCK',
			code:"3"
		},{
			name:'NG->OK',
			code:"4"
		}
		]
		,selectedStatus:"0"
		,remark:""
		,allCount:{todoCount:0,okCount:0,ngCount:0,blockCount:0,ngToOkCount:0,totalCount:0}
		,taskData:{}
		,selectedModuleIndex:-1
		,hoverModuleIndex:-1
		,moduleData:[]
		,addGroup:{taskId:$("#taskId").val()}
		,taskGroupData:[]
		,allTaskGroupData:[]
		,projectTaskData:[]
		,emptyModule:{id:0,name:'无所属分组'}
		,moveToGroupId:null
		,moveToTaskId:null
		,originalGroupId:null
	}
	,methods:{
		init:function(){
			this.queryCase();
			this.queryProject();
			this.loadTypeData();
			this.loadLevelData();
			this.queryAllCount();
			this.queryGroup();
			this.queryTask();
		}
		,queryTask:function(){
			var vm = this;
			$.ajax({
				url :staticURL+'/testcase/testTask/listAll?activeFlag=1',
				dataType : 'json',
				success : function(json) {
					if(json.length){
						vm.projectTaskData = (json);
					}
				}
			});
		}
		,queryTaskGroup:function(value){
			var vm = this;
			vm.allTaskGroupData = [{id:0,name:'无所属分组'}];
			vm.moveToTaskId = value;
			$.ajax({
				url :staticURL+'/testcase/taskGroup/listAll?taskId='+value,
				dataType : 'json',
				success : function(json) {
					if(json.length){
						vm.allTaskGroupData = vm.allTaskGroupData.concat(json);
					}
				}
			});
		}
		,mergeGroup:function(group){
			app.originalGroupId = group.id;
			app.openCloseDialog('taskMoveGroupForm',true);
		}
		,moveToGroup:function(){
			if(app.moveToTaskId){
	        	var ids = new Array();
				for(var i=0;i<app.selectedCase.length;i++){
					ids.push(app.selectedCase[i].id)
				}
				$.ajax({
					url : staticURL+"/testcase/taskCase/updateGroupId?ids="+ids+"&taskGroupId="+app.moveToGroupId+"&originalGroupId="+app.originalGroupId+"&moveToTaskId="+app.moveToTaskId,
					dataType : 'json',
					success : function(r) {
						if (r.success) {
							app.$message({showClose: true,
						          message: r.msg,
						          type: 'success',
						          position: 'top'});
							app.queryCase();
							$(".el-main")[0].scrollTop=0
							app.openCloseDialog('taskMoveGroupForm',false);
						} else {
							app.$message({showClose: true,
						          message: r.msg,
						          type: 'error',
						          position: 'top'});
						}
					}
				});
			}
		}
		,doAddGroup:function(){
			this.openCloseDialog('taskGroupForm',true);
		}
		,queryGroup:function(){
			var vm = this;
			$.ajax({
				url :staticURL+'/testcase/taskGroup/listAll?taskId='+vm.taskId,
				dataType : 'json',
				success : function(json) {
					vm.taskGroupData = json;
				}
			});
		}
		,doUpdateGroup:function(){
			var url = staticURL+'/testcase/taskGroup/add'
			if(app.addGroup.id){
				url = staticURL+'/testcase/taskGroup/edit'
			}
			$.ajax({
				url : url,
				data : app.addGroup,
				dataType : 'json',
				success : function(r) {
					if (r.success) {
						app.$message({showClose: true,
					          message: r.msg,
					          type: 'success',
					          position: 'top'});
						app.openCloseDialog('taskGroupForm',false);
						app.queryGroup();
					} else {
						app.$message({showClose: true,
					          message: r.msg,
					          type: 'error',
					          position: 'top'});
					}
				}
			});
		}
		,clickModule:function(module,index){
			if(module){
				app.queryCaseData.taskGroupId = module.id;
				app.originalGroupId = module.id;
			}else{
				app.queryCaseData.taskGroupId = null;
				app.originalGroupId = null;
			}
			app.selectedModuleIndex = index;
			app.queryCase();
			app.hoverModuleIndex = index;
			$(".el-main")[0].scrollTop=0
		}
		,doUpdateModule:function(group){
			this.openCloseDialog('taskGroupForm',true);
			this.addGroup.id = group.id;
			this.addGroup.name = group.name;
		}
		,doDeleteModule:function(group){
			app.$confirm('当前分组「'+group.name+'」会被删除，用例会同时也会被删除。此操作不可撤销，是否确定？', '删除模块', {
		          confirmButtonText: '确定',
		          cancelButtonText: '取消',
		          type: 'warning'
	        }).then(function () {
	        	$.ajax({
					url : staticURL+"/testcase/taskGroup/delete?ids="+group.id,
					dataType : 'json',
					success : function(r) {
						if (r.success) {
							app.$message({showClose: true,
						          message: r.msg,
						          type: 'success',
						          position: 'top'});
							app.queryGroup();
						} else {
							app.$message({showClose: true,
						          message: r.msg,
						          type: 'error',
						          position: 'top'});
						}
					}
				});
	        }).catch(function (action) {
	        	  //取消
	        });
		}
		,goFrontend:function(){
			window.location.href=staticURL+"/frontend"
		}
		,goBackend:function(){
			window.open(staticURL+'/backend');
		}
		,queryAllCount:function(){
			var vm = this;
			$.ajax({
				url :staticURL+'/testcase/testTask/getAllCount.do?id='+vm.taskId+"&taskGroupId="+(vm.queryCaseData.taskGroupId==null?'':vm.queryCaseData.taskGroupId),
				dataType : 'json',
				success : function(json) {
					vm.allCount.todoCount = json.todoCount;
					vm.allCount.okCount = json.okCount;
					vm.allCount.ngCount = json.ngCount;
					vm.allCount.blockCount = json.blockCount;
					vm.allCount.ngToOkCount = json.ngToOkCount;
					var totalCount = (vm.allCount.todoCount+
							vm.allCount.okCount+
							vm.allCount.ngCount+
							vm.allCount.blockCount+
							vm.allCount.ngToOkCount);
					vm.allCount.todoRate = (((vm.allCount.todoCount==0?0:vm.allCount.todoCount)/totalCount)*100).toFixed(2)+"%"
					vm.allCount.okRate = (((vm.allCount.okCount==0?0:vm.allCount.okCount)/totalCount)*100).toFixed(2)+"%"
					vm.allCount.ngRate = (((vm.allCount.ngCount==0?0:vm.allCount.ngCount)/totalCount)*100).toFixed(2)+"%"
					vm.allCount.blockRate = (((vm.allCount.blockCount==0?0:vm.allCount.blockCount)/totalCount)*100).toFixed(2)+"%"
					vm.allCount.ngToOkRate = (((vm.allCount.ngToOkCount==0?0:vm.allCount.ngToOkCount)/totalCount)*100).toFixed(2)+"%"
				}
			});
		}
		,queryProject:function(){
			var vm = this
			$.ajax({
				url :staticURL+'/testcase/caseProject/listAll.do',
				data : vm.queryPorjectData,
				dataType : 'json',
				success : function(json) {
					app.porjectDatagird = json;
				}
			});
		}
		,queryModule:function(param){
			var vm = this
			var projectId = param;
			if(!param){
				projectId = vm.libraryCode;
			}
			$.ajax({
				url :staticURL+'/testcase/caseModule/listAll.do?activeFlag=1&projectId='+projectId,
				dataType : 'json',
				success : function(json) {
					if(!param){
						app.moduleData = json;
					}else{
						app.moduleSelectData = json;
					}
				}
			});
		}
		,tableCellStyle:function({row, column, rowIndex, columnIndex}){
			if(columnIndex == 4){
				if(row.level=='P1'){
					return 'color:#F56C6C'
				}
				if(row.level=='P2'){
					return 'color:#409EFF'
				}
				if(row.level=='P3'){
					return 'color:#67C23A'
				}
				if(row.level=='P4'){
					return 'color:#DCDFE6'
				}
				return ''
			}
		}
		,handleSizeChange:function(val){
			app.queryCaseData.rows=val;
			app.queryCase();
			$(".el-main")[0].scrollTop=0
		}
		,handleCurrentChange:function(val){
			app.queryCaseData.page=val;
			app.queryCase();
			$(".el-main")[0].scrollTop=0
		}
		,handlePrevClick:function(val){
			app.queryCaseData.page=val;
			app.queryCase();
			$(".el-main")[0].scrollTop=0
		}
		,handleNextClick:function(val){
			app.queryCaseData.page=val;
			app.queryCase();
			$(".el-main")[0].scrollTop=0
		}
		,queryCase:function(){
			var vm = this
			$.ajax({
				url :staticURL+'/testcase/taskCase/datagrid.do',
				data : vm.queryCaseData,
				dataType : 'json',
				success : function(json) {
					app.caseDatagrid = json.rows;
					app.totalNum = json.total;
			        app.queryAllCount();
				}
			});
		}
		,datagridDbclick:function(row, event){
			app.openCloseDialog('caseAddForm',true);
			app.addCase = JSON.parse(JSON.stringify(row));
			app.isEdit = true;
			app.queryModule(app.addCase.libraryCode);
		}
		,datagridClick:function(row, event, column){
			app.currentCase = row;
			this.datagridDbclick(row);
		}
		,handleSelectionChange:function(val){
			app.selectedCase = val;
		}
		,openCloseDialog:function(formName,openOrNot){
			if(formName=='caseAddForm'){
				app.dialogConfig.caseAddDialogVisible=openOrNot;
			}else if(formName=='statusForm'){
				app.dialogConfig.statusDialogVisible=openOrNot;
				app.remark='';
			}else if(formName=='taskUpdateForm'){
				app.dialogConfig.taskDialogVisible=openOrNot;
			}else if(formName=='taskGroupForm'){
				app.dialogConfig.taskGroupVisible=openOrNot;
				app.addGroup.id = null;
			}else if(formName=='taskMoveGroupForm'){
				app.dialogConfig.taskMoveGroupVisible=openOrNot;
			}
			if(!openOrNot){
				app.resetForm(formName)
			}
			app.operateFormName = formName;
		}
		,resetForm:function(formName) {
			if(app.$refs[formName]){
				app.$refs[formName].resetFields();
			}
	    }
		,submitForm:function(formName){
			app.$refs[formName].validate(function(res){
				if(res){
					//验证通过
					$.ajax({
						url : staticURL+'/testcase/taskCase/edit',
						data : app.addCase,
						dataType : 'json',
						success : function(r) {
							if (r.success) {
								app.$message({showClose: true,
							          message: r.msg,
							          type: 'success',
							          position: 'top'});
								app.openCloseDialog(formName,false);
								app.queryCase(r);
							} else {
								app.$message({showClose: true,
							          message: r.msg,
							          type: 'error',
							          position: 'top'});
							}
						}
					});
				}
			});
		}
		,libraryChange:function(data){
			var vm = this
			vm.porjectDatagird.find(function(item){
				if(item.id==data){
					vm.addData.libraryName = item.name
					return;
				}
			})
		    app.addCase.moduleCode = 0
			app.addCase.moduleName = '无所属模块'
			app.queryModule(data);
		}
		,moduleChange:function(data){
			var vm = this;
			vm.moduleSelectData.find(function(item){
				if(item.name==data){
					vm.addData.moduleCode = item.id
					return;
				}
			}) 
		}
		,loadTypeData:function(){
			var vm = this
			vm.loadSelectData('A02');
		}
		,loadLevelData:function(){
			var vm = this
			vm.loadSelectData('A03');
		}
		,loadSelectData:function(parentCode){
			var vm = this
			$.ajax({
				url :staticURL+'/basic/baseInfoAction/combox?parentCode='+parentCode,
				dataType : 'json',
				success : function(json) {
					if(parentCode=='A01'){
						vm.libraryData = json;
					}else if(parentCode=='A02'){
						vm.typeData = json;
					}else if(parentCode=='A03'){
						vm.levelData = json;
					}else{
						vm.moduleData = json;
					}
				}
			});
		}
		,doDeleteCase:function(){
			app.$confirm('确定删除所选中用例吗？', '删除用例', {
		          confirmButtonText: '确定',
		          cancelButtonText: '取消',
		          type: 'warning'
	        }).then(function () {
	        	var ids = new Array();
				for(var i=0;i<app.selectedCase.length;i++){
					ids.push(app.selectedCase[i].id)
				}
				$.ajax({
					url : staticURL+"/testcase/taskCase/delete?ids="+ids,
					dataType : 'json',
					success : function(r) {
						if (r.success) {
							app.$message({showClose: true,
						          message: r.msg,
						          type: 'success',
						          position: 'top'});
							app.queryCase();
						} else {
							app.$message({showClose: true,
						          message: r.msg,
						          type: 'error',
						          position: 'top'});
						}
					}
				});
	        }).catch(function (action) {
	        	  //取消
	        });
			
		}
		,updateStatusBatch:function(){
			var ids = new Array();
			for(var i=0;i<app.selectedCase.length;i++){
				ids.push(app.selectedCase[i].id)
			}
			$.ajax({
				url : staticURL+"/testcase/taskCase/updateStatusBatch?ids="+ids+"&status="+app.selectedStatus,
				data:{remark:app.remark},
				dataType : 'json',
				success : function(r) {
					if (r.success) {
						app.$message({showClose: true,
					          message: r.msg,
					          type: 'success',
					          position: 'top'});
						app.openCloseDialog('statusForm',false)
						app.queryCase();
					} else {
						app.$message({showClose: true,
					          message: r.msg,
					          type: 'error',
					          position: 'top'});
					}
				}
			});
		}
		,formatterStatus:function(row, column, cellValue, index){
			if(row.status == '0'){
				return 'TODO';
			}else if(row.status == '1'){
				return 'OK';
			}else if(row.status == '2'){
				return 'NG';
			}else if(row.status == '3'){
				return 'BLOCK';
			}else if(row.status == '4'){
				return 'NG->OK';
			}
		}
		,statusType(row){
			if(row.status == '0'){
				return '';
			}else if(row.status == '1' || row.status == '4'){
				return 'success';
			}else if(row.status == '2'){
				return 'warning';
			}else if(row.status == '3'){
				return 'danger';
			}
		}
		,doDeleteTask(){
			app.$confirm('当前正在删除测试计划，此操作不可撤销，是否删除？', '删除用例', {
		          confirmButtonText: '确定',
		          cancelButtonText: '取消',
		          type: 'warning'
	        }).then(function () {
				$.ajax({
					url : staticURL+"/testcase/testTask/deletePt?ids="+app.taskId,
					dataType : 'json',
					success : function(r) {
						if (r.success) {
							app.$message({showClose: true,
						          message: r.msg,
						          type: 'success',
						          position: 'top'});
							app.goFrontend();
						} else {
							app.$message({showClose: true,
						          message: r.msg,
						          type: 'error',
						          position: 'top'});
						}
					}
				});
	        }).catch(function (action) {
	        	  //取消
	        });
		}
		,opendTaskDialog:function(){
			app.openCloseDialog('taskUpdateForm',true);
			app.taskData.id = app.taskId;
			app.taskData.name = app.taskName;
		}
		,doUpdateTask:function(){
			app.$refs['taskUpdateForm'].validate(function(res){
				if(res){
					//验证通过
					$.ajax({
						url : staticURL+'/testcase/testTask/edit',
						data : app.taskData,
						dataType : 'json',
						success : function(r) {
							if (r.success) {
								app.$message({showClose: true,
							          message: r.msg,
							          type: 'success',
							          position: 'top'});
								app.taskName = app.taskData.name;
								app.openCloseDialog('taskUpdateForm',false);
							} else {
								app.$message({showClose: true,
							          message: r.msg,
							          type: 'error',
							          position: 'top'});
							}
						}
					});
				}
			});
		}
		,visibleChange:function(visible,row,index){
			if(!visible){
				row.editStatus=false;
				row.title=row.title+' ';
			}
		}
		,changeColumnStatus:function(row,value,update,index){
			row.editStatus=value;
			row.title=row.title+' ';
			if(app.$refs['tableSelect'+index]){
				console.log(app.$refs['tableSelect'+index]);
				app.$nextTick(function(){
					app.$refs['tableSelect'+index].handleFocus();
				})
			}
			if(!value && update){
				//更新
				var ids = new Array();
				ids[0] = row.id;
				$.ajax({
					url : staticURL+"/testcase/taskCase/updateStatusBatch?ids="+ids+"&status="+row.status,
					data:{remark:app.remark},
					dataType : 'json',
					success : function(r) {
						if (r.success) {
							app.$message({showClose: true,
						          message: r.msg,
						          type: 'success',
						          position: 'top'});
							app.queryAllCount();
						} else {
							app.$message({showClose: true,
						          message: r.msg,
						          type: 'error',
						          position: 'top'});
						}
					}
				});
			}
		}
	}
	,created: function () {
		this.init();
		window.addEventListener('keydown', function (e) {
		    if (e.keyCode === 37) {
		      // 左
		      app.handleNextClick((app.queryCaseData.page-1)>1?(app.queryCaseData.page-1):1);
			} else if (e.keyCode === 39) {
		      // 右
			  app.handlePrevClick((app.queryCaseData.page+1)>app.totalPage?(app.totalPage):(app.queryCaseData.page+1));
		    }
		})
	}
	,computed:{
		totalPage:function(){
			if(!app.queryCaseData || !app.queryCaseData.rows || !app.totalNum){
				return 1;
			}
			var div = parseInt(app.totalNum/app.queryCaseData.rows);
			var sub = app.totalNum%app.queryCaseData.rows;
			if(sub == 0){
				return div;
			}
			return div+1;
		}
	}
});
});